package com.jiyinit.web.core.mobile.controller;

import com.alibaba.fastjson.JSONObject;
import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户头像相关
 * @author liuzongguang
 * @create 2018/7/11 9:20
 */

@Controller
@RequestMapping("/mobile/avatar")
public class MuserAvatarController {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MuserAvatarController.class);

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

     /**
      * 用户上传头像
      * @param request
      * @return
      * @throws NoSuchMethodException
      * @throws InvocationTargetException
      * @throws IllegalAccessException
      * @throws IOException
      */
     @RequestMapping("/toSetUserAvatar")
     @ResponseBody
     public ResponseEntity<ResponseDto> toSetUserAvatar(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException{
         String requestJson = request.getParameter("request_json");
         if(Check.isNullStr(requestJson))
         {
             return new ResponseEntity<>(ResponseDto.responseFail("参数异常"), HttpStatus.OK);
         }
         JSONObject requestObj = JSONObject.parseObject(requestJson);

         Object userId = requestObj.get("userId");
         if(Check.isNullObj(userId))
         {
             return new ResponseEntity<>(ResponseDto.responseFail("用户编号不能为空"), HttpStatus.OK);
         }
         Object imgStr  = requestObj.get("imgStr");
         if(Check.isNullObj(imgStr))
         {
             return new ResponseEntity<>(ResponseDto.responseFail("用户头像不能为空"), HttpStatus.OK);
         }

         String picName=userId+"_"+getTodaySec()+".jpg";
         //String picName=userId+".jpg";
         String picPath = (String) PropertyPlaceholderConfigurer.getContextProperty("USER_AVATAR");
         String imgFile = request.getSession().getServletContext().getRealPath("")+"/"+picPath+picName;
         BASE64Decoder decoder = new BASE64Decoder();
         // Base64解码
         byte[] b = decoder.decodeBuffer(imgStr.toString());
         for (int i = 0; i < b.length; ++i) {
             if (b[i] < 0) {// 调整异常数据
                 b[i] += 256;
             }
         }
         // 生成jpeg图片
         String imgFilePath = imgFile;
         OutputStream out = new FileOutputStream(imgFilePath);
         out.write(b);
         out.flush();
         out.close();

         //图片名称
         TabCoreUserEntity user = new TabCoreUserEntity();
         user.setUserId(Integer.parseInt(userId.toString()));
         user.setAvatar(picName);

         Map<String,String> resultMap=new HashMap<String,String>();
         try{
             int result=userService.updateUserAvatar(user);
             if(result>0)
             {
                 resultMap.put("avatarUrl",picPath+picName);
             }
             else
             {
                 resultMap.put("avatarUrl","");
             }
             return new ResponseEntity<>(ResponseDto.responseOK(resultMap), HttpStatus.OK);
         }catch(Exception e){
             LOGGER.info(e.toString());
             resultMap.put("avatarUrl","");
             return new ResponseEntity<>(ResponseDto.responseOK(resultMap), HttpStatus.OK);
         }
     }
     // 获得当前日小时
     public static String getTodaySec(){
         Date date = new Date();
         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
         String returnDate = sdf.format(date);
         return returnDate;
     }
}
